<template>
  <div style="width: 100%;font-size: 10px;">
    <!-- <el-card> -->
    <div style="margin-bottom: 10px; ">
      <el-form :inline="true">
        <el-row :gutter="5" class="formRow">
          <el-col :span="7" class="formCol" style="margin-left: 5%;">
            <el-form-item label="Metric" class="formLabel">
              <el-select v-model="Form.metric" class="formSelect" size="small " placeholder="请选择Metric" clearable filterable @change="metricChange">
                <el-option v-for="metric in metric_list" :key="metric.id" :label="metric.name" :value="metric.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="formCol">
            <el-form-item label="聚合函数" class="formLabel">
              <input v-model="checkAll" type="checkbox" @click="checkedAll">
              <span>全选</span>
              <template v-for="(checkOne,index) in checkList">
                <input :id="checkOne.id" :key="index" v-model="checkOne.state" style="margin-left: 10px;" type="checkbox" @click="checkedOne(checkOne)">
                <span :key="checkOne.name">{{ checkOne.name }}</span>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="4" class="formCol" style="width: 20%;">
            <el-form-item label="刷新间隔">
              <el-input v-model="refreshtime" size="small " style="width: 40%;" />
              <label>秒</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5" class="formRow">
          <el-col :span="20" class="formCol" style="margin-left: 5%;">
            <label class="tagLabel">标签</label>
            <div id="showTagsDiv" class="tagDiv" />
            <div v-show="isShow" id="tagSelectDiv" class="tagDiv">
              <el-select v-model="Tags.tag_key" class="tagSelect" size="small " placeholder="选择键" clearable filterable @change="tagKeyChange">
                <el-option v-for="(tag_key, i) in key_list" :key="i" :label="tag_key" :value="tag_key" />
              </el-select>
              <el-select v-model="Tags.tag_val" class="tagSelect" size="small " placeholder="选择值" clearable filterable>
                <el-option v-for="(tag_val, j) in val_list" :key="j" :label="tag_val" :value="tag_val" />
              </el-select>
              <el-button type="infor" size="small " icon="el-icon-plus" @click="addTag">添加标签</el-button>
            </div>
            <el-button v-show="bottonShow" style="margin-left: 20px; margin-top: 7px; float:left;" type="success" size="small " icon="el-icon-plus" @click="addTagsInit" />
          </el-col>
          <el-col :span="2" style="margin-left: 2%;">
            <el-button type="primary" size="small " icon="el-icon-search" @click="search">查询</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-row :gutter="10">
        <el-col :span="24">
          <div id="muliLineChart" :style="{width: '98%', height: '500px'}" />
        </el-col>
      </el-row>
    </div>
    <!-- </el-card> -->
  </div>
</template>

<script>
// import axios from 'axios'
import axiosservice from '@/utils/CommonData.js'
import { formatDate } from '@/utils/time.js'
// import '@/assets/css/metricSearch.css'
// 在组件引入基本模板
import * as echarts from 'echarts'
// import { Message } from 'element-ui'
// 在组件引入柱状图组件
require('echarts/lib/chart/line')
export default {
  name: 'Echarts',
  data() {
    return {
      metrictagstree: null,
      refreshtime: 3,
      timerId: null,
      lineEchart: null,
      status: ' ',
      colorArray: ['#3499DD', '#32C5D3', '#E7505A', '#C59F46', '#8F44AD', '#70AD46', '#CB660A', '#A7B7CC', '#3499DD', '#32C5D3', '#E7505A', '#C59F46', '#8F44AD', '#70AD46', '#CB660A', '#A7B7CC'],	//
      metric_list: [],
      key_list: [],
      val_list: [],
      tagHtml: '',
      isShow: false,
      bottonShow: true,
      lineDatas: [],
      checkList: [
        { state: true, id: 'max', name: '最大值' },
        { state: true, id: 'min', name: '最小值' },
        { state: true, id: 'avg', name: '平均值' },
        { state: false, id: 'sum', name: '求和' },
        { state: false, id: 'var', name: '方差' }],
      // {"min":["0.04"],"avg":["50.43"],"max":["99.96"],"var":["813077.09"],"sum":["50377.27"],"timestamp":["1621002153"]}
      Form: {
        metric: '',
        tag: ''
      },
      Tags: {
        tag_key: '',
        tag_val: ''
      }
    }
  },
  computed: {
    checkAll: function() {
      return this.checkRes.length === this.checkList.length
    },
    checkRes: function() {
      var res = []
      this.checkList.forEach(function(one) {
        if (one.state == true) {
          res.push(one.name)
        }
      })
      return res
    }
  },
  mounted() {
    // 开始加载
    // const loading = this.$loading({
    //   lock: true, // lock的修改符--默认是false
    //   text: '拼命加载中，请稍候...', // 显示在加载图标下方的加载文案
    //   background: 'rgba(0,0,0,0.8)', // 遮罩层颜色
    //   spinner: 'el-icon-loading' // 自定义加载图标类名
    // })
    var _this = this
    _this.getMetrics()
    // _this.getMetricTagTree()
    // _this.getTagKeys()
    // _this.getTagValues()
    // 获取数据显示成功后，关闭loading
    // loading.close()
  },
  // beforeCreate() {
  //   console.log('beforeCreate', this.timerId)
  //   if (this.timerId != null) {
  //     clearInterval(this.timerId)
  //   }
  // },
  created() {
    const _this = this
    window.delTag = _this.delTag
  },
  beforeDestroy() {
    if (this.lineEchart != null) {
      echarts.dispose(this.lineEchart)
    }
    clearInterval(this.timerId)
    this.timerId = null
  },
  methods: {
    metricChange(metric) {
      console.log('metricChange', metric)
      this.key_list.splice(0)
      this.val_list = []
      if (this.metrictagstree[metric]) {
        for (var p1 in this.metrictagstree[metric]) {
          this.key_list.push(p1)
        }
      }
      console.log('key_list', this.key_list)
      this.Tags.tag_key = ''
      this.Tags.tag_val = ''
    },
    tagKeyChange(tagkey) {
      console.log('tagKeyChange', tagkey)
      this.val_list = this.metrictagstree[this.Form.metric][tagkey]
      console.log('val_list', this.val_list)
      this.Tags.tag_val = ''
      console.log('this.Tags', this.Tags)
    },
    getMetricTagTree() {
      axiosservice({
        url: '/metrictagstree',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            if (res.data.code == 200) {
              this.metrictagstree = JSON.parse(res.data.data)
              this.metricChange(this.Form.metric)
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取tag数据失败!')
        })
    },
    getMetrics() {
      // axios.get('/api/metrics')
      axiosservice({
        url: '/api/metrics',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const result = res.data
            this.Form.metric = result[0] // 默认值取第一个
            for (var index in result) {
              this.metric_list.push({
                'id': index,
                'name': result[index]
              })
            }
            this.getMetricTagTree()
            // this.Form.metric = result[1] // 默认值取第一个
          // console.log(this.metric_list.length)
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取metrics数据失败!')
        })
    },
    addTagsInit() {
      this.isShow = true
      this.bottonShow = false
    },
    addTag() {
      // var id = this.Tags.tag_key + '_' + this.Tags.tag_val
      var text = this.Tags.tag_key + '=' + this.Tags.tag_val
      if (text == '=') {
        this.isShow = false
        this.bottonShow = true
        return
      }
      if (this.Form.tag == '') {
        this.Form.tag = text
      } else {
        this.Form.tag += ',' + text
      }
      this.tagHtml += '<label style="margin-left:5px;border: 1px solid #00557f;">' + text + '<i style="cursor:pointer;padding-left:5px;" class="remove el-icon-remove" onClick="delTag(\'' + text + '\')" ></i> </label>'// <button style="cursor:pointer;padding-left:5px;"  onClick="delTag(\''+text+'\')">'+text+'<i style="cursor:pointer;padding-left:5px;"  class="remove el-icon-remove" @click="delTag(\''+this.Tags.tag_key+'='+this.Tags.tag_val+'\')"></i></button>';
      this.isShow = false
      this.bottonShow = true
      var div = document.getElementById('showTagsDiv')
      div.innerHTML = this.tagHtml
    },
    delTag(id) {
      var tag1 = this.Form.tag.replace(id + ',', '')
      var tag2 = this.Form.tag.replace(',' + id, '')
      if (this.Form.tag == tag1) {
        if (this.Form.tag == tag2) {
          this.Form.tag = this.Form.tag.replace(id, '')
        } else {
          this.Form.tag = this.Form.tag.replace(',' + id, '')
        }
      } else {
        this.Form.tag = this.Form.tag.replace(id + ',', '')
      }
      var delHtml = '<label style="margin-left:5px;border: 1px solid #00557f;">' + id + '<i style="cursor:pointer;padding-left:5px;" class="remove el-icon-remove" onClick="delTag(\'' + id + '\')" ></i> </label>'// <button style="cursor:pointer;padding-left:5px;"  onClick="delTag(\''+text+'\')">'+text+'<i style="cursor:pointer;padding-left:5px;"  class="remove el-icon-remove" @click="delTag(\''+this.Tags.tag_key+'='+this.Tags.tag_val+'\')"></i></button>';
      this.tagHtml = this.tagHtml.replace(delHtml, '')
      this.isShow = false
      this.bottonShow = true
      var div = document.getElementById('showTagsDiv')
      div.innerHTML = this.tagHtml
    },
    getTagKeys() {
      // axios.get('/api/tagk')
      axiosservice({
        url: '/api/tagk',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const data = res.data
            for (var index in data) {
              this.key_list.push({
                'id': index,
                'name': data[index]
              })
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取tag-key数据失败!')
        })
    },
    getTagValues() {
      // axios.get('/api/tagv')
      axiosservice({
        url: '/api/tagv',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const data = res.data
            for (var index in data) {
              this.val_list.push({
                'id': index,
                'name': data[index]
              })
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取tag-value数据失败!')
        })
    },
    checkedOne(one) {
      one.state = !one.state
    },
    checkedAll() {
      var _this = this
      var checkType = (_this.checkAll == true) // 循环中(true == this.checkAll)的结果会发生改变
      _this.checkList.forEach(function(one, index) {
        if (checkType == true) {
          // 已经全选 走取消的逻辑
          _this.checkList[index].state = false
          // _this.Form.taglist = [];
        } else {
          // 没有全选 走选中的逻辑
          _this.checkList[index].state = true
          // _this.Form.taglist.push(one.id);
        }
      })
      //  this.showLine();
    },
    search() {
      if (this.Form.metric == '') {
        alert('请选择metric进行查询！')
        return false
      }
      let n = 0
      for (let j = 0; j < this.checkList.length; j++) {
        const agg = this.checkList[j]
        if (agg.state) {
          n++
        }
      }
      if (n == 0) {
        alert('请勾选要查看的Aggregator！')
        return false
      }
      this.lineEchart = echarts.init(document.getElementById('muliLineChart'))
      this.lineEchartInit(this.lineEchart, '实时计算', [], [], [])
      this.refreshData()
      if (this.timerId != null) {
        console.log('clearInterval', this.timerId)
        clearInterval(this.timerId)
        this.timerId = null
      }
      this.timerId = setInterval(this.refreshData, this.refreshtime * 1000)
    },
    refreshData() {
      const m = this.Form.metric// testmetric1
      // const t = this.Form.tag == '' || this.Form.tag == null ? '' : '&tags=(' + this.Form.tag + ')'// (tag1=0,tag2=1)
      this.tableData = []
      // /redisclient?metric=testmetric1&tags=(tag1=0,tag2=1)
      // axios.get('/redisclient?metric=' + m + t)
      const t = this.Form.tag == '' || this.Form.tag == null ? '' : '(' + this.Form.tag + ')'// (tag1=0,tag2=1)
      axiosservice({
        url: '/redisclient',
        method: 'get',
        params: {
          metric: m,
          tags: t
        }
      })
        .then((res) => {
          // console.log(res)
          res = res.data
          if (res.code == 200) {
            const xData = []
            const series = []
            const legendData = []
            this.lineDatas[0] = { id: 'max', value: res.max }
            this.lineDatas[1] = { id: 'min', value: res.min }
            this.lineDatas[2] = { id: 'avg', value: res.avg }
            this.lineDatas[3] = { id: 'sum', value: res.sum }
            this.lineDatas[4] = { id: 'var', value: res.var }
            console.log(res)
            for (var tt in res.timestamp) {
              // console.log(res.timestamp[tt]) //这里的tt是下标
              const tf = formatDate(new Date(res.timestamp[tt] * 1000), 'hh:mm:ss') // 10位时间戳需要*1000
              xData.push(tf)
            }
            for (var i = 0; i < this.checkList.length; i++) {
              const agg = this.checkList[i]
              if (agg.state) {
                const name = agg.name
                let lineData = []
                for (var j = 0; j < this.lineDatas.length; j++) {
                  if (this.lineDatas[j].id == agg.id) {
                    lineData = this.lineDatas[j].value
                  }
                }
                legendData.push(name)
                series.push({
                  name: name,
                  type: 'line',
                  data: lineData
                })
              }
            }
            // this.refreshData(this.lineEchart, xData, legendData, series)
            var option = this.lineEchart.getOption()
            // console.log(option)
            const newxAxis = {
              type: 'category',
              boundaryGap: false,
              data: xData,
              axisLabel: {
                interval: 0,
                rotate: 40
              },
              textStyle: {
                fontSize: 8
              }
            }
            option.xAxis = newxAxis
            option.legend = { data: legendData }
            option.series = series
            this.lineEchart.setOption(option, true)
            // this.lineDraw('muliLineChart', '实时计算', xData, legendData, series)
          } else if (res.code == 0) {
            this.$message.error('筛选条件错误!')
            if (this.timerId != null) {
              console.log('筛选条件错误clearInterval', this.timerId)
              clearInterval(this.timerId)
              this.timerId = null
            }
            if (this.lineEchart != null) {
              echarts.dispose(this.lineEchart)
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('实时计算接口调用失败!')
        })
    },
    lineEchartInit(line, title, xData, legendData, series) {
      // 绘制图表配置
      const option = {
        grid: {
          top: 50,
          bottom: 40,
          left: 70,
          right: 40
        },
        color: this.colorArray,
        title: {
          text: title
        },
        tooltip: {
          trigger: 'axis'
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xData
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        legend: { data: legendData },
        series: series
      }
      // 窗口大小自适应方案
      line.setOption(option)
      setTimeout(function() {
        window.onresize = function() {
          line.resize()
        }
      }, 200)
    }
  }
}
</script>

<style>
@charset "UTF-8";
.formRow{
  height: 40px;
  line-height: 40px;
  margin-bottom: 1px;
}
.formCol{
  height: 40px;
  line-height: 40px;
/* background-color:#e8e8e8; */
}
.formLabel{
  margin-right: 50px;
  font-size:14px;
  padding-left: 10px;
  text-align: left;
  width: 100%;
  border: 1px solid #F8F6F6;
}

.formSelect{
  margin-left: 40%;
  width: 120%;
}
.tagLabel{
  padding-left: 10px;
  text-align: left;
  float:left;
}
label{
  font-size: 14px
}
.tagSelect{
  /* margin-left: 10px; */
  width: 100px;

}
.tagDiv{
  height: 40px;
  line-height: 40px;
  float:left;
  margin-left: 13px;
}
</style>
